let http = require("http");
let fs = require("fs");
let url = require("url");
let path = require('path');

//获取轮播图接口 /sliders

let sliders = require('./sliders');

function readJsonFile(callBack){
  fs.readFile('./book.json','utf-8',function (err, data) {
    // console.log("read json length "+JSON.parse(data));
    if(err || data.length ==0){//如果有错误 或者没有内容,返回空的数组
      callBack([]);
    }else{
      callBack(JSON.parse(data));//将读出来的内容转化为对象
    }
  });
}
//修改 删除后写入文件
function write(content,callBack){
  fs.writeFile('./book.json',JSON.stringify(content),callBack);
}

//测试是否成功
/*readJsonFile(function(books){
  //books代表所有图书
  console.log(books);
})*/
/*write("df",function(){
  //books代表所有图书
})*/
let pageSize = 5;//每页固定5条
http.createServer((req,res)=>{
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
  res.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.setHeader("X-Powered-By",' 3.2.1')
  if(req.method=="OPTIONS") return res.end();/*让options请求快速返回*/

  let {pathname,query} = url.parse(req.url,true);//true 把query转换为对象
  //轮播图
  if(pathname === '/sliders'){
    res.setHeader("Content-Type","application/json;charset=utf8");
    return res.end(JSON.stringify(sliders));
  }
  //热门图书 http://localhost:3000/hot
  if(pathname === '/hot'){
    res.setHeader("Content-Type","application/json;charset=utf8");
    readJsonFile(function(books){
      //books代表所有图书
      let hot = books.reverse().slice(0,6);
      setTimeout(()=>{
        res.end(JSON.stringify(hot));
      },2000);//
    });
    return
  }

  if(pathname === '/page'){
    let offset = parseInt(query.offset) || 0;//取出的是字符串,分页字符串
    console.log(offset)
    readJsonFile(function(books){
      //books代表所有图书
      res.setHeader("Content-Type","application/json;charset=utf8");
      books.reverse();//倒序
      let result = books.slice(offset,offset + pageSize);
      let hasMore = true;
      if(books.length <= (offset + pageSize)){//大于总长度
        hasMore = false;
      }
      res.end(JSON.stringify({hasMore,books:result}));
    });
    return;
  }
  //rest接口 http://localhost:3000/book
  if(pathname === '/book'){
    let id = parseInt(query.id);//取出的是字符串
    switch (req.method){//?id=1
      case 'GET':
        if(!isNaN(id)){//查询一个
          readJsonFile(function(books){
            //books代表所有图书
            res.setHeader("Content-Type","application/json;charset=utf8");
            // let book = books.filter(item=>item.bookId===id);
            //filter返回的book没有发送到前台
            let book = books.find(item=>item.bookId===id);
            if(!book) book = {};
            console.log(book)
            res.end(JSON.stringify(book));
          });
        }else {//undefined的话 获取所有book
          readJsonFile(function(books){
            //books代表所有图书
            res.setHeader("Content-Type","application/json;charset=utf8");
            let hot = books.reverse().slice(0,6);
            res.end(JSON.stringify(hot));
          });
        }
        break;
      case 'POST':
          let str = '';
          req.on("data",chunk=>{
            str+=chunk;
          });
          req.on('end',()=>{
            let book = JSON.parse(str);//反序列化的对象
            readJsonFile(function(books){
              //books代表所有图书
              res.setHeader("Content-Type","application/json;charset=utf8");
              book.bookId = books.length?books[books.length - 1].bookId + 1:1;//添加id
              books.push(book);//内存中添加一本书
              write(books,function () {
                res.end(JSON.stringify(book));//返回修改的数据，前台也没有去使用
              });
            });
          });
        break;
      case 'PUT':
        if(id){ //要修改的id
          let str = '';
          req.on("data",chunk=>{
            str+=chunk;
          });
          req.on('end',()=>{
            let book = JSON.parse(str);//反序列化的对象
            readJsonFile(function(books){
              //books代表所有图书
              res.setHeader("Content-Type","application/json;charset=utf8");
              books = books.map(item=>{
                if(item.bookId == id){
                  return book;//返回什么就替换什么
                }else{
                  return item;//不修改的直接返回
                }
              });
              write(books,function () {
                res.end(JSON.stringify(book));//返回修改的数据，前台也没有去使用
              });
            });
          });
        }
        break;
      case 'DELETE':
        console.log("ready delete" + id);
        readJsonFile(function(books){
          //books代表所有图书
          books = books.filter(item=>item.bookId !== id);
          console.log("after delte "+books.length);
          write(books,function () {
            res.end(JSON.stringify({}));//删除返回空对象
          })
        });
        break;
    }

    return
  }

  //挂载静态文件
  console.log('.' + pathname);
  fs.stat('.' + pathname,function (err, stats) {
    if(err){
      /*res.statusCode = 404;
      res.end('not found');*/
      fs.createReadStream('index.html').pipe(res);
    }else {
      // console.log(stats);
      fs.createReadStream('.' + pathname).pipe(res);
      /*if (stats.isDirectory){ /index.html   /static/css 等全部进入isDirectory里面去了

        let p = path.join('.' + pathname,'./index.html');
        // console.log(p.toString());
        fs.createReadStream('./index.html').pipe(res);
      }else {
        console.log(pathname);
        fs.createReadStream('.' + pathname).pipe(res);
      }*/

    }
  });
}).listen(3000);
